<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件

// 验证Hash密码
function checkPasswordHash($password, $password_hash) {
	return (new \Security\PasswordHash(8, false)) -> CheckPassword($password, $password_hash);
}

/*
 * 获取数据league_parameters表的全局参数
 * @value key 键
 * @value 是否直接从数据库取数据
 */
function getFarmParam($key = null, $is_test = false) {
	if($is_test) {
		$params = false;
	} else {
		$params = \think\Cache::get('farm_parameters');
	}

	if(!$params) {
		$getParameters = \app\common\model\FarmParameters::all();

		$params = array();
		if($getParameters) {
			foreach($getParameters as $v) {
				$params[$v -> key] = $v -> value;
			}
			clearFarmParam();
			\think\Cache::set('farm_parameters', $params);
		}

		if(!is_null($key) && !isset($params[$key])) {
			return null;
		}
	}

	if(is_null($key)) {
		return $params;
	} else {
		return isset($params[$key])?$params[$key]:getFarmParam($key, true);
	}
}

function clearFarmParam() {
	\think\Cache::rm('farm_parameters');
}

/**
 * 计算天数
 */
function countDays($start = null, $end = null) {
	if($start) {
		$startTime = date_create(date('Y-m-d', $start));
	} else {
		$startTime = date_create(date('Y-m-d'));
	}

	if($end) {
		$endTime = date_create(date('Y-m-d', $end));
	} else {
		$endTime = date_create(date('Y-m-d'));
	}
	
	return (int)date_diff($startTime, $endTime) -> format('%R%a days');
}

/*
 * 生成随机数
 */
function crypto_rand($min, $max, $pedantic = true) {
    $diff = $max - $min;
    if ($diff <= 0) return $min; // not so random...
    $range = $diff + 1; // because $max is inclusive
    $bits = ceil(log(($range),2));
    $bytes = ceil($bits/8.0);
    $bits_max = 1 << $bits;
    // e.g. if $range = 3000 (bin: 101110111000)
    //  +--------+--------+
    //  |....1011|10111000|
    //  +--------+--------+
    //  bits=12, bytes=2, bits_max=2^12=4096
    $num = 0;
    do {
        $num = hexdec(bin2hex(openssl_random_pseudo_bytes($bytes))) % $bits_max;
        if ($num >= $range) {
            if ($pedantic) continue; // start over instead of accepting bias
            // else
            $num = $num % $range;  // to hell with security
        }
        break;
    } while (True);  // because goto attracts velociraptors
    return $num + $min;
}